package com.cc.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2023-03-22 12:53
 */
public class FileUtil {
    public static String getFileType(MultipartFile file) {
        String filename = file.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        return filename.substring(index + 1);
    }

    public static String getFileType(File file) {
        String filename = file.getName();
        int index = filename.lastIndexOf(".");
        return filename.substring(index + 1);
    }

    public static File convertMultipartFileToFile(MultipartFile multipartFile, String prefix, String suffix) throws IOException {
        File file = File.createTempFile(prefix, suffix);
        multipartFile.transferTo(file);
        return file;
    }

    public static List<File> writeFileSlices(File sourceFile, String targetDir, int sliceSize, int uploadedSlices, RedisUtil redisUtil, String fileMd5) throws IOException {
        long fileLength = sourceFile.length();
        String name = sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf("."));
        String fileType = FileUtil.getFileType(sourceFile);
        List<File> slices = new ArrayList<>();

        for (int i = 0; i < fileLength; i += sliceSize) {
            try (RandomAccessFile randomAccessFile = new RandomAccessFile(sourceFile, "r")) {
                randomAccessFile.seek(i);
                byte[] bytes = new byte[sliceSize];
                int len = randomAccessFile.read(bytes);

                String tmpPath = targetDir + File.separator + name + File.separator + (i / sliceSize + 1) + "." + fileType;
                File tmpFile = new File(tmpPath);
                File parentFile = tmpFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }

                try (FileOutputStream fileOutputStream = new FileOutputStream(tmpFile)) {
                    fileOutputStream.write(bytes, 0, len);
                }

                slices.add(tmpFile);

                // 更新Redis中的上传进度
                int currentSliceNo = i / sliceSize + 1;
                if (currentSliceNo > uploadedSlices) {
                    redisUtil.putHash(fileMd5 + "_slices", currentSliceNo, tmpPath);
                }
            }
        }

        return slices;
    }
}
